package com.qy.controller.manage;

import com.github.pagehelper.PageHelper;
import com.qy.base.core.*;
import com.qy.base.utils.DateUtil;
import com.qy.base.utils.ExcelUtil.ExcelLogs;
import com.qy.base.utils.ExcelUtil.ExcelUtil;
import com.qy.base.utils.UploadFile;
import com.qy.model.Policy;
import com.qy.model.Unit;
import com.qy.service.UnitService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by zaq on 2018/07/10.
 */
@RestController("Manage-UnitController")
@RequestMapping("/manage/unit")
public class UnitController {
    @Resource
    private UnitService unitService;

    //政策库-单位列表-新增
    @PostMapping("/add")
    public Result add(@RequestBody Unit unit) {
        if (unit.getUnit_name() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getCharge_name() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getBusiness_scope() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getProvince() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getUnit_tel() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getUrl() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        unit.setPublisher("平台");
        unit.setAdd_time(String.valueOf(new Date().getTime()));
        unitService.save(unit);
        return ResultGenerator.successResult();
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Integer id) {
        unitService.deleteById(id);
        return ResultGenerator.successResult();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Unit unit) {
        unitService.update(unit);
        return ResultGenerator.successResult();
    }

    @GetMapping("/detail")
    public Result detail(@RequestParam Integer id) {
        Unit unit = unitService.findById(id);
        return ResultGenerator.successResult(unit);
    }

    @GetMapping("/list")
    public Result list(PageBean<Unit> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Unit> list = unitService.findAll();
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //政策库-单位列表
    @GetMapping("/unitList")
    public Result unitList(PageBean<Map> page, Integer type, String content, Unit unit) {
        if (type == null || type == 0) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        } else if (type == 1) {
            unit.setUnit_name(content);
        } else if (type == 2) {
            unit.setCharge_name(content);
        } else if (type == 3) {
            unit.setUnit_tel(content);
        } else if (type == 4) {
            unit.setPublisher(content);
        }
        PageHelper.startPage(page.getPageNum(), page.getSize(), "add_time desc");
        List<Map> list = unitService.unitList(unit);
        page.setList(list);
//        if (list.size() == 0){
//            return ResultGenerator.errResult(1,"查询结果不存在");
//        }
        return ResultGenerator.successResult(page);
    }

    //政策库-单位列表-编辑-保存
    @PostMapping("/updateUnit")
    public Result updateUnit(@RequestBody Unit unit) {
        if (unit.getId() == null || unit.getId() == 0) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        if (unit.getUnit_name() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getCharge_name() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getBusiness_scope() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getProvince() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getUnit_tel() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        if (unit.getUrl() == null) {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        unitService.updateUnit(unit);
        return ResultGenerator.successResult();
    }

    //政策库-单位列表-删除
    @PostMapping("/deleteUnit")
    public Result deleteUnit(@RequestBody Unit unit) {
        if (unit.getId() == null || unit.getId() == 0) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        unitService.deleteUnit(unit);
        return ResultGenerator.successResult();
    }

    //政策库-单位列表-编辑按钮
    @GetMapping("/seeUnit")
    public Result seeUnit(Unit unit) {
        if (unit.getId() == null || unit.getId() == 0) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        List<Unit> list = unitService.selectUnitById(unit);
        return ResultGenerator.successResult(list.get(0));
    }

    //政策库-单位列表-上下架
    @PostMapping("/unitState")
    public Result unitState(@RequestBody Unit unit) {
        if (unit.getId() == null || unit.getId() == 0) {
            throw new ServiceException(Constants.CODE_ERR_PARAM_ID);
        }
        unitService.unitState(unit);
        return ResultGenerator.successResult();
    }

    //政策库-政策-新增-获取所有单位
    @GetMapping("/selectUnitName")
    public Result selectUnitName() {
        List<Map> list = unitService.selectUnitName();
        return ResultGenerator.successResult(list);
    }
    //政策库-政策-新增-获取输入参数的单位 模糊搜索
    @GetMapping("/selectVagueUnitName")
    public Result selectVagueUnitName(String unit_name, PageBean<Map> page) {
        PageHelper.startPage(page.getPageNum(), page.getSize());
        List<Map> list = unitService.selectVagueUnitName(unit_name);
        page.setList(list);
        return ResultGenerator.successResult(page);
    }

    //导入
    @PostMapping("/Import")
    public Result Import(@RequestBody Unit unit) throws Exception {
        String fileUrl = null;
        if (unit.getExcel() != null && !unit.getExcel().isEmpty()) {
            fileUrl = UploadFile.uploadBase64(unit.getExcel());
        } else {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }

        File f = new File("../" + fileUrl);
        InputStream inputStream = new FileInputStream(f);

        ExcelLogs logs = new ExcelLogs();
        Collection<Map> importExcel = ExcelUtil.importExcel(Map.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0);

        if (importExcel.size() != 0) {
            for (Map m : importExcel) {
                Unit unit1 = new Unit();
                unit1.setUnit_name(m.get("单位名称").toString());
                unit1.setCharge_name(m.get("负责人").toString());
                if (m.get("办公地址（原表头为业务范围，现更改为办公地址。）") != null && !m.get("办公地址（原表头为业务范围，现更改为办公地址。）").toString().isEmpty()) {
                    unit1.setBusiness_scope(m.get("办公地址（原表头为业务范围，现更改为办公地址。）").toString());
                }
                unit1.setProvince(m.get("所在省份（由原招商地区拆分而来）").toString());
                if (m.get("所在地市（由原招商地区拆分而来）") != null && !m.get("所在地市（由原招商地区拆分而来）").toString().isEmpty()) {
                    unit1.setCity(m.get("所在地市（由原招商地区拆分而来）").toString());
                }
                if (m.get("所在区县（由原招商地区拆分而来）") != null && !m.get("所在区县（由原招商地区拆分而来）").toString().isEmpty()) {
                    unit1.setCounty(m.get("所在区县（由原招商地区拆分而来）").toString());
                }
                unit1.setUnit_tel(m.get("单位电话").toString());
                unit1.setUrl(m.get("网站").toString());
//                List<Unit> list = unitService.selectUnitByName(unit1);
//                if (list.size() == 0) {
                unit1.setPublisher("平台");
                unit1.setAdd_time(DateUtil.getNowTimestamp());
                unitService.save(unit1);
//                } else {
//                    throw new ServiceException(Constants.CODE_EXIST_UNIT);
//                }
            }
        } else {
            throw new ServiceException(Constants.CODE_ERR_PARAM);
        }
        return ResultGenerator.successResult();
    }
}
